import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({
  showSpinner: false
})

const whiteList = ['/404', '/401'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  const userToken = getToken() || ''
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  if (userToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // 如果当前页面是dashboard 将不会触发afterEach钩子，需手动处理它
    } else {
      // 判断当前用户是否已拉取完user_info信息
      if (store.getters.roles.length === 0 || store.getters.permissions.length === 0) {
        store.dispatch('GetUserInfoAndPermissions').then(res => {
          store.dispatch('GenerateRoutes').then(() => { // 根据roles权限生成可访问的路由表
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to, replace: true })
          })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next(false)
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(false)
      window.location.href = process.env.SSO_LOGIN + encodeURIComponent(window.location.href) + '&appCode=' + process.env.APP_CODE
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
